package webshop.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import javax.transaction.UserTransaction;

import webshop.data.Product;

/**
 * Servlet the controls(fills) stock on products.
 * @author Ohm & Zim.
 */
public class ProductStockManagerServlet extends AbstractSuperServlet {

    @Resource
    UserTransaction tx;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        EntityManager em = emf.createEntityManager();

        try {
            tx.begin();
            // parameters
            String selectedProduct = request.getParameter("productname");
            int addToStock = Integer.valueOf(request.getParameter("stockincresement"));
            boolean productFound = false;

            // Checks for product
            PersonUtil personUtil = new PersonUtil(em, request);
            Product product = personUtil.findProduct(selectedProduct);
            if (product != null) {
                product.increseStock(addToStock);
            } else {
                out.println("Product not found!");
            }
            tx.commit();
            out.println("Productstock increased in DB for: " + product.getName() + " by: "
                    + addToStock + " items.");
            out.println("<meta http-equiv=Refresh content=2;url=adminPage.html> ");
            out.println("<br/>");
            out.println("Redirect in 2 sec.");
        } catch (Exception e) {
            out.println(e.getMessage());
        } finally{
            out.close();
        }
    }
} 

